package cn.vote.service;

import java.sql.Date;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.message.BasicNameValuePair;

import cn.vote.domain.Voter;
import cn.vote.uitls.*;

import cn.vote.uitls.HttpPostUtil;
import cn.vote.uitls.JsonResult;

public class LoginService {
	public static JsonResult login(String username,String password){
		String urlOne = "http://123.207.16.33:8088/Authorization/GetToken?signKey=ROwHiKBA&signValue=v0X9Npv1fHE3zDTl";	
		String jsonStr =  HttpPostUtil.httpPostOne(urlOne);		
		JSONObject jsonObject = JSON.parseObject(jsonStr);
		String data = jsonObject.getString("Data");

		if (!data.trim().isEmpty()) {
			String urlTwo = "http://123.207.16.33:8088/Authorization/GetData";
			 //封装参数
	         List<NameValuePair> params = new ArrayList<NameValuePair>();
	         params.add(new BasicNameValuePair("UserCode", username));
	         params.add(new BasicNameValuePair("Pwd",password));
	         params.add(new BasicNameValuePair("Token", data));
	         String httpPost = HttpPostUtil.httpPost(urlTwo, params);
	         /*
	          * 得到返回的json中success是否为true，判断是否返回成功
	          */
	         JSONObject jsonReal = JSON.parseObject(httpPost);
	         String success = jsonReal.getString("Success");
	         if (success.equals("true")) {
				String jsonDataStr = jsonReal.getString("Data");
				JSONObject jsonData = JSON.parseObject(jsonDataStr);
				
				Voter voter = new Voter();
				voter.setUsername(username);
				voter.setPassword(password);
				
				return new JsonResult(JsonResultType.Success, "登录成功！", null,voter);
	        }
		}
		return new JsonResult(JsonResultType.QueryNull, "登录失败！用户名或密码错误！");
	}
}
